package com.common.base.tools.utils

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch

/**
 * 三疯
 * *************************
 *
 * *************************
 */
object TimerCountDown {
    //    var timerS = MutableLiveData<Int>()
    var timerDown = MutableSharedFlow<Int>()
    private lateinit var countDownJob: Job

    private fun start(lifecycleOwner: LifecycleOwner, time: Int) {
        countDownJob = lifecycleOwner.lifecycleScope.launch {
            // 在这个范围内启动的协程会在Lifecycle被销毁的时候自动取消
            (time downTo 0).forEach {
                delay(1000)
                timerDown.emit(it)
            }
        }
    }

    fun reStart(lifecycleOwner: LifecycleOwner, time: Int = 17) {
        if (this::countDownJob.isInitialized) {
            cancel()
            start(lifecycleOwner, time)
        } else {
            start(lifecycleOwner, time)
        }
    }

    fun cancel() {
        if (this::countDownJob.isInitialized)
            countDownJob.cancel()
    }
}